package com.briup.jz.service.impl;

import com.briup.jz.bean.Category;
import com.briup.jz.bean.CategoryExample;
import com.briup.jz.bean.extend.CategoryExtend;
import com.briup.jz.dao.CategoryMapper;
import com.briup.jz.dao.extend.CategoryExtendMapper;
import com.briup.jz.service.ICategoryService;
import com.briup.jz.utils.CustomerException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 潘京博
 * @project: jz
 * @description: 栏目业务实现类
 * @create: 2020/6/13 11:08
 */
@Service
public class CategoryServiceimpl implements ICategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private CategoryExtendMapper categoryExtendMapper;

    @Override
    public List<Category> findAll() {
        return categoryMapper.selectByExample(new CategoryExample());
    }

    @Override
    public void saveOrUpdate(Category category) {
        if(category.getId() != null){
            // 修改，先判断该id对应的数据是否存在
            Category categoryCheck = categoryMapper.selectByPrimaryKey(category.getId());
            if(categoryCheck == null){
                //  不存在，报错！
                throw new CustomerException("更新失败，要更新的数据不存在");
            }
            // 存在，更新
            categoryMapper.updateByPrimaryKey(category);
        } else {
            // 新增
            categoryMapper.insert(category);
        }
    }

    @Override
    public void deleteById(long id) {
        // 先判断该id对应的数据是否存在
        Category category = categoryMapper.selectByPrimaryKey(id);
        if(category == null){
            // 当不存在，报错！
            throw new CustomerException("删除失败，要删除的数据不存在");
        }
        // 当存在，删除
        categoryMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<CategoryExtend> findAllWithChildren() {
        return categoryExtendMapper.selectAllWithChildren();
    }

    @Override
    public Category findById(long id) {
        return categoryMapper.selectByPrimaryKey(id);
    }
}
